package cn.edu.scau.disk.service.impl;

import cn.edu.scau.disk.exception.CommonException;
import cn.edu.scau.disk.mapper.UserMapper;
import cn.edu.scau.disk.pojo.User;
import cn.edu.scau.disk.service.UserService;
import cn.edu.scau.disk.utils.RedisConstant;
import cn.edu.scau.disk.utils.RedisUtil;
import cn.edu.scau.disk.utils.TokenGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceimpl implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String login(String username, String password) throws CommonException {
        User user=userMapper.selectOne(new QueryWrapper<User>()
                    .eq("username",username)
                    .eq("password",password));
        if (user==null)
            throw new CommonException("用户名不存在或密码错误");
        String token= TokenGenerator.generateValue();
        redisUtil.set(RedisConstant.TOKEN+token,String.valueOf(user.getId()));
        return token;
    }

    @Override
    public void register(String username, String password, String confimpass) throws CommonException {
        if (!password.equals(confimpass)) throw new CommonException("两次密码不一致");
        User user=userMapper.selectOne(new QueryWrapper<User>()
                .eq("username",username));
        if (user != null)
            throw new CommonException("用户名已存在");
        User u=new User(username,password);
        userMapper.insert(u);
    }

    @Override
    public void logout(String token) {
        redisUtil.del(RedisConstant.TOKEN+token);
    }

    @Override
    public void resetPwd(Integer userId, String oldPwd, String newPwd, String confirmPwd) throws CommonException {
        User u = userMapper.selectById(userId);
        if(!u.getPassword().equals(oldPwd)){
            throw new CommonException("原密码不正确");
        }
        if (!newPwd.equals(confirmPwd)) {
            throw new CommonException("两次输入的新密码不相同");
        }
        u.setPassword(newPwd);
        userMapper.updateById(u);
    }
}
